const animations = {};

export const ANIMATION_INTERVAL = 1000 / 60;

export const requestAnimationFrame = (func) => {
	if (window.requestAnimationFrame) {
		window.requestAnimationFrame(func);
	} else {
		setTimeout(func, ANIMATION_INTERVAL);
	}
};

export const clearUniqueAnimate = (name) => {
	animations[name] = null;
};

/**
 * Dedup-able animate function.
 * When one interval register func in same name, only call the last one.
 * @param func
 * @param name
 */
export const uniqueAnimate = (name, func) => {
	// Mark current function is the main animation
	animations[name] = func;

	function doStep() {
		requestAnimationFrame(() => {
			// Kill current animation if not active
			if (animations[name] !== func) return;

			const result = func();
			if (result === true) {
				doStep();
			} else {
				clearUniqueAnimate(name);
			}
		});
	}

	doStep();
};
